//
//  OAuthViewController.swift
//  SinaWeiBo
//
//  Created by guozeqian on 16/3/2.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController{

    let client_id = "639075404"
    let redirect_uri = "http://www.baidu.com"
    let client_secret = "3f7e700036ea71e5a7f739d854df385b"
    let webView = UIWebView()
    
    //MARK: 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '13001116184' , document.getElementById('passwd').value = '121516';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func loadView() {
        
        view = webView
        webView.delegate = self

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        
        loadOauthPage()
    }

    
    private func loadOauthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
         webView.loadRequest(request)
    }
    
    private func setUpUI(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: "fullAccount")
    }

    
}

extension OAuthViewController:UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        //是网页请求页面 或者请求授权页面
        if urlString.hasPrefix("https://api.weibo.com") {
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        //程序走到这里  一定包含了  回调的url
        guard let query = request.URL?.query else {
            return false
        }
        
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        loadAccessToken(code)
        
        return true

    }
    private func loadAccessToken(code:String){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            if let dict = result as? [String: AnyObject]{
                let account = UserAccount(dict:dict)
                self.loadUserInfo(account)

            }
            
            }) { (_, error) -> Void in
                print(error)
        }
        
        
    }
    
    private func loadUserInfo(account:UserAccount){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parmaters = ["access_token": account.access_token!, "uid": account.uid!]

        let AFN = AFHTTPSessionManager()
        AFN.POST(urlString, parameters: parmaters, success: { (_, result) -> Void in
            if let  dict = result as? [String: AnyObject]{
                account.avatar_large = dict["avatar_large"] as? String
                account.name = dict["name"] as? String
                account.saveAccount()
            }
            
            
            }) { (_, error) -> Void in
                print(error)
        }

    }
    
    
    
}















